<template>
    <div>
        <div ref="experimentContainer"></div>

    </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios'
const router = useRouter();
const lastscore = ref(0);
const life = ref(3);
const scores = ref(0);
const timeline = ref([]);
let level = 21;
let responnumber = ['7', '8', '9', '4', '5', '6', '1', '2', '3', '0', "回退"]
let size = [4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12]
let range = [
    1000, 300, 1000, 300, 1000, 300, 1000, 300,
    1000, 300, 1000, 300, 1000, 300, 1000, 300,
    1000, 300
]
const nowstep = ref(0);
const inputvalue = ref("");
const correctNumbers = ref();
import { useAuthStore } from '../store/index';
const Store = useAuthStore();
let id = Store.user.stuId;
const getAssetsFile = (url) => {
    return new URL(`${url}`, import.meta.url).href
}
onMounted(async () => {
    Store.setuptrue();
    axios({
        method: "get",
        url: `/interface/res/score-visualArrayTask-max`,
        params: {
            stuId: id,
            type: "reverse"
        }
    }).then(async (res) => {
        if (res.data.data != null) {

            lastscore.value = res.data.data.score
        }
        console.log(lastscore.value);
        await init();
        var images = [getAssetsFile('../img/blue.png'), getAssetsFile('../img/white.png'), getAssetsFile('../img/black.png'), getAssetsFile('../img/yellow.png'), getAssetsFile('../img/green.png'), getAssetsFile('../img/red.png'),
        getAssetsFile('../img/purple.png'), getAssetsFile('../img/instructions.png')
        ]
        console.log(timeline.value);
        jsPsych.init({
            timeline: timeline.value,
            preload_images: images,
            // on_finish: function () {
            //     jsPsych.data.displayData(); // comment out if you do not want to display results at the end of task
            // }
        });
    })




    // var start = {
    //     type: 'html-button-response',
    //     stimulus: `
    //     <h1>最高分：${lastscore.value}</h1>
    //     <p class="jsp">指导语;欢迎来挑战视觉数字闯关</p>
    //     <p class="jsp">记住屏幕上挨个出现的数字，一会在答案按出现顺序输入。</p>
    //     <p class="jsp">游戏里，你一共有三点生命，关卡挑战失败就会扣减一点</p>
    //     <p class="jsp">加油获得最高分吧!</p>`,
    //     choices: ['开始游戏'],
    //     prompt: ``
    // };
    // var new_timeline = {
    //     timeline: [start]
    // }

    // jsPsych.addNodeToEndOfTimeline(new_timeline)

    // addrespon()
    // addrespon()
})
const init = () => {
    return new Promise((resolve) => {
        var enter_fullscreen = {
            type: 'fullscreen',
            message:"<h1>进入全屏</h1><br/>",
            button_label:"继续",
            fullscreen_mode: true
        }
        timeline.value.push(enter_fullscreen);
        var start = {
            type: 'html-button-response',
            stimulus: `
        <h1>最高分：${lastscore.value}</h1>
  
        <p class="jsp">请判断第二次出现的目标颜色块是否与第一次的一致，一致按“√”，不一致按“×”</p>
`,
            choices: ['开始游戏'],
            prompt: ``
        };
        timeline.value.push(start);
        var levelitem = {
            timeline: dealitem(0, 4, 1000)
        }
        timeline.value.push(levelitem);
        resolve();
    })
}
const dealitem = (item1, item2, item3) => {
    const randomNumber = Math.round(Math.random());
    var fixation = {
        type: 'html-keyboard-response',
        stimulus: '<div style="font-size:40px;">+</div>',
        choices: jsPsych.NO_KEYS,
        trial_duration: 900
    }
    let result = [];
    var start = {
        type: 'html-button-response',
        stimulus: `<h1>第${Math.floor(nowstep.value / 3) + 1}关第${nowstep.value % 3 + 1}小关</h1>`,
        choices: ["<h1>继续</h1>"],
        // trial_duration: 1000,
        prompt: ``,

    };
    result.push(start);
    var item = {
        type: 'visual-array-stimuli',
        set_size: item2,
        target_size: [30, 30],
        trial_duration: item3,  
        on_start: function (){
            console.log(this)
        }
    };

    var resopen = {
        type: "visual-array-response",
        target_size: [30, 30],
        choices: ['k', 's'],
        locs: function () {
            var h = jsPsych.data.get().last(2).values()[0].locations
            return h
        },
        cols: function () {
            var h = jsPsych.data.get().last(2).values()[0].colours
            return h
        },
        target_different: function () {
            return randomNumber
        },
        trial_duration: null,
        on_start: function () {
            console.log(jsPsych.data.get().last(2).values()[0].locations);
        },
        on_finish: function (data) {
            // console.log(data);
        }
    };
    var feedback = {
        type: 'html-keyboard-response',
        stimulus:  function () {
            const timestamp = Date.now(); // 获取当前时间戳
            const date = new Date(timestamp); // 使用时间戳创建一个 Date 对象

            // 获取时、分、秒
            const hours = date.getHours().toString().padStart(2, '0'); // 获取小时，并确保始终是两位数
            const minutes = date.getMinutes().toString().padStart(2, '0'); // 获取分钟，并确保始终是两位数
            const seconds = date.getSeconds().toString().padStart(2, '0'); // 获取秒，并确保始终是两位数

            // 构建时间字符串
            const timeString = `${hours}:${minutes}:${seconds}`;
             axios({
                method: "post",
                url: `/interface/res/visual-array-task`,
                data: {
                    "duration": range[Math.floor(nowstep.value / 3)],
                    "level": Math.floor(nowstep.value / 3),
                    "score": scores.value,
                    "size": size[Math.floor(nowstep.value / 3)],
                    "time": timeString,
                    "stuId": id,
                }
            }).then(async (res) => {
                console.log(res);
            })
            var text = ""
            var accuracy = jsPsych.data.get().last(1).values()[0].correct
            if (accuracy) {
                scores.value++;
                nowstep.value++;
                if (nowstep.value == 54) {
                    success()
                } else {
                    if (nowstep.value % 3 == 0) {
                        gotostep()
                    }
                }
                switch (life.value) {
                    case 3:
                        text += `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img"></div><div style="font-size:35px; color:rgb(0 130 0)"><b>选择正确</div>`
                        break;
                    case 2:
                        text += `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img"></div><div style="font-size:35px; color:rgb(0 130 0)"><b>选择正确</div>`
                        break;
                    case 1:
                        text += `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img"></div><div style="font-size:35px; color:rgb(0 130 0)"><b>选择正确</div>`
                        break;
                    default:
                        break;
                }

            } else {
                nowstep.value--;
                if (nowstep.value < 0) {
                    nowstep.value = 0
                }

                back();
                switch (life.value) {
                    case 3:
                        text += `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img"></div><div style="font-size:35px; color:rgb(180 0 0)"><b>选择错误</div>`
                        break;
                    case 2:
                        text += `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img"></div><div style="font-size:35px; color:rgb(180 0 0)"><b>选择错误</div>`
                        break;
                    case 1:
                        text += `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img"></div><div style="font-size:35px; color:rgb(180 0 0)"><b>选择错误</div>`
                        break;
                    default:
                        break;
                }
                life.value--;
            }
            if (life.value != 0) {


                var levelitem = {
                    timeline: dealitem(0, size[Math.floor(nowstep.value / 3)], range[Math.floor(nowstep.value / 3)])
                }
                console.log(levelitem);
                jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
            } else {
                dead();
            }
            console.log(text);
            //text += '<div style="font-size:30px; color:rgb(0 0 0)"><br><br>现在开始新试验.</div>'
            return text
        },
        choices: jsPsych.NO_KEYS,
        trial_duration: 1000,

    }
    result.push(fixation);
    result.push(item);
    result.push(fixation);
    result.push(resopen);
    result.push(feedback);

    return result;
}
function gotostep() {
    var start = {
        type: 'html-button-response',
        stimulus: `
        <h1>很棒，恭喜过关！</h1>
        <img src="${new URL(`../assets/gotostep.png`, import.meta.url).href}" alt="">
        <h1>已闯过${Math.floor(nowstep.value / 3) }关</h1>
       `,
        choices: [`进入第${Math.floor(nowstep.value / 3) + 1}关`],
        prompt: ``
    };
    var levelitem = {
        timeline: [start]
    }
    console.log(levelitem);
    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
}
function dead() {
    var start = {
        type: 'html-button-response',
        stimulus: `
        <h1>你的挑战机会用完了，下次再挑战吧!</h1>
        <h1>得分${scores.value}</h1>
        <img src="${new URL(`../assets/dead.png`, import.meta.url).href}" alt="" >
        <h1>已闯过${Math.floor(nowstep.value / 3) }关</h1>`,
        choices: ['退出游戏'],
        prompt: ``,
        on_finish: function () {
            router.push('/select')
        }
    };
    var levelitem = {
        timeline: [start]
    }
    console.log(levelitem);
    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
}
function back() {
    var start = {
        type: 'html-button-response',
        stimulus: `
        <h1>没有过关，请继续努力!</h1>
        <img src="${new URL(`../assets/back.png`, import.meta.url).href}" alt="" >
        <h1>第${Math.floor(nowstep.value / 3) + 1}关</h1>`,
        choices: ['重新闯关'],
        prompt: ``
    };
    var levelitem = {
        timeline: [start]
    }
    console.log(levelitem);
    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
}
function success() {
    var start = {
        type: 'html-button-response',
        stimulus: `
        <h1>恭喜你全部闯关成功</h1>
        <img src="${new URL(`../assets/success.png`, import.meta.url).href}" alt="" >
        <h1>第${Math.floor(nowstep.value / 3) + 1}关</h1>`,
        choices: ['返回'],
        prompt: ``,
        on_finish: function () {
            router.push('/select')
        }
    };
    var levelitem = {
        timeline: [start]
    }
    console.log(levelitem);
    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
}
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

function generateUniqueRandomNumbers(min, max, count) {
    const uniqueNumbers = new Set();
    while (uniqueNumbers.size < count) {
        uniqueNumbers.add(Math.floor(Math.random() * (max - min + 1)) + min);
    }
    return Array.from(uniqueNumbers);
}


</script>
<style>
.jsp {
    font-size: 2rem;
}

.jspsych-btn {
    font-size: 1.5rem;
}

#jspsych-html-button-response-btngroup {
    display: grid;
    justify-content: center;
    grid-template-columns: repeat(3, 50px);
    grid-auto-rows: 50px;
    gap: 5px;
}

button {
    padding: 10px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f0f0f0;
    cursor: pointer;
}

button:hover {
    background-color: #e0e0e0;
}


#imgbox {
    height: 20px;
    width: 300px;
    position: fixed;
    right: 0px;
    top: 0px;
}

#imgbox img {
    width: 30%;
}

.score {
    position: fixed;
    left: 0px;
    top: 0px;
}
</style>